﻿using System.Collections.Generic;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;

namespace LiJ.Common.Plugs.ConfigPlug
{
    public class DefaultConfigPlug : IConfigPlug
    {
        private readonly string _configPath;

        private IConfiguration _configuration;

        public IConfiguration Configuration
        {
            get
            {
                if (_configuration != null) return _configuration;
                var configBuilder = new ConfigurationBuilder().Add(new JsonConfigurationSource()
                {
                    Path = _configPath,
                    ReloadOnChange = true
                });
                _configuration = configBuilder.Build();
                return _configuration;
            }
            set => _configuration = value;
        }

        /// <summary>
        /// 配置文件构造函数
        /// </summary>
        /// <param name="configPath">配置文件路径</param>
        public DefaultConfigPlug(string configPath = null)
        {
            _configPath = configPath ?? "appsettings.json";
        }

        /// <summary>
        /// 根据节点名称获取节点
        /// </summary>
        /// <param name="key">节点名称</param>
        /// <returns></returns>
        public IConfigurationSection GetSection(string key)
        {
            return Configuration?.GetSection(key);
        }

        /// <summary>
        /// 获取配置文件节连接字符串
        /// </summary>
        /// <param name="name">连接字符串名称</param>
        /// <returns></returns>
        public string GetConnectionString(string name)
        {
            return Configuration.GetConnectionString(name);
        }

        /// <summary>
        /// 获取配置文件子节点
        /// </summary>
        /// <returns></returns>
        public IEnumerable<IConfigurationSection> GetChildren()
        {
            return Configuration?.GetChildren();
        }
    }
}